package com.heima.admin.logaspect;

import com.alibaba.fastjson.JSON;
import com.heima.admin.interceptor.AppUserIdHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @创建人: stone
 * @描述: 通知类
 */

//通知类必须配置成Spring管理的bean
@Component
//设置当前类为切面类类
@Aspect
public class ControllerAspect {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public void sendErrMsg(String topic,Object data) {
        kafkaTemplate.send("ERR_MSG_"+topic, "log", JSON.toJSONString(data));
    }

    public void sendEndMsg(String topic,Object data) {
        kafkaTemplate.send("END_MSG_"+topic, "log", JSON.toJSONString(data));
    }

    //设置切入点，@Pointcut注解要求配置在方法上方
    @Pointcut("execution(* com.heima.admin.controller.v1.*.*(*))")
    private void contarllerPointcut() {
    }

    //环绕通知
    @Around("contarllerPointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //处理异步发送消息值
        HashMap<String,Object> hashMap = new HashMap();
        hashMap.put("runMethod",pjp.getSignature().getName());//方法名
        hashMap.put("calssName",pjp.getTarget().getClass().getSimpleName());//类名
        hashMap.put("args",pjp.getArgs());//参数
        hashMap.put("operatingCrew",AppUserIdHolder.get());//当前处理人id
        //放行
        Object ret = null;
        try {
            ret = pjp.proceed();
        } catch (Throwable e) {
            hashMap.put("exception",e);//记录异常
            //异步处理
            sendErrMsg("LOG",hashMap);
            throw e;
        }
        hashMap.put("methodReturn",ret);//记录返回值
        //异步处理
        sendEndMsg("LOG",hashMap);
        return ret;
    }
}
